﻿
//服务器只负责单纯的转发
var userMgr = require("./usermgr");
var sr = require("./server");
//等待房间，在此房间内玩家准备战斗
var waitingrooms = new Array();
//战斗房间，每隔一秒会检测其中所有的玩家的状态
var fightingrooms = new Array();
//邀请好友房间
let invitingRooms = new Array();
var util = require('../utils/util');
var c = require('./config.json');
var nowTime = new Date().getTime();
//目前主要房间功能只需要
// 1.进入等待房间，退出等待房间
// 2.进入战斗房间，退出战斗房间
// 3.将战斗开始时，将发兵情况和玩家状态进行广播
// 4.如果接受到玩家死亡消息，则游戏结束
//modiftyUserAIbalance->getRealPlayerNumber
// gy
var userState = {    
    idle: 0,
    ready: 1,
    fight: 2,
    build: 3,
    leave: 4,
    invite: 5,

};



exports.isUesrAlreadyInRoom = function (user, room) {
    for (var i = 0; i < room.length; ++i) {
        if (room[i] == user) {
            return true;
        }
        else {
            if (room[i].userId == user.userId) {
                console.log("玩家重复登录");
                return true;
            }
        }
    }
    return false;
}
/**从准备房间中获取一个其他玩家 */
exports.getOtherUserInRoom = function (user, room, userstate) {
    for (var i = 0; i < room.length; ++i) {
        //判断是玩家自己
        if (room[i].userId == user.userId)
            continue;
        if (room[i].userState == userstate) {
            return room[i];
        }

    }
    //console.log("没有等待的用户");
    return null;
}

/************************************************************************************* */
/*** 准备界面 */
/*目前是两人对战版本，所以每次进入的是两个人*/
exports.EnterWaitingRoom = function (user) {
    //判断参数是否正常
    if (user == null) {
        console.log("玩家为空");
        return 6;
    }
    //判断参数是否正确
    if (exports.isUesrAlreadyInRoom(user, waitingrooms)) {
        console.log("玩家已经存在watingroom");
        return 7;
    }
    //判断是否反复加入房间
    //usermg.resetPlayer(user);
    user.userState = userState.ready;
    user.watingStartTime = nowTime;
    waitingrooms.push(user);
    console.log(user.userId + "玩家进入watingroom");
    return 0;
}

// exports.find
exports.ExitWaitingRoom = function (user) {
    if (user == null) {
        console.log("玩家为空");
        return false;
    }
    if (!exports.isUesrAlreadyInRoom(user, waitingrooms)) {
        console.log("玩家不存在watingroom");
        return false;
    }
    console.log(user.userId + "号玩家退出waitingrooms");
    //waitingrooms.splice(util.findIndexEx(waitingrooms, user.userId), 1);
    let index = waitingrooms.indexOf(user);
    waitingrooms.splice(index, 1);

}


//1.将符合条件的玩家进行配对
//2.将匹配过得玩家进行删除
exports.waitingroomsUpdate = function () {
    var usrTmp;
    var difTimeTmp;

    //将所有玩家进行配对
    for (var i = 0; i < waitingrooms.length; ++i) {
        usrTmp = exports.getOtherUserInRoom(waitingrooms[i], waitingrooms, userState.ready);
        if (usrTmp == null) {
            //console.log("准备房间内不存在其他玩家与" + waitingrooms[i].userId + "玩家匹配");
            continue;
        }
        if (exports.connectUsers(usrTmp, waitingrooms[i])) {
            console.log(waitingrooms[i].userId + "与" + usrTmp.userId + "绑定成功");
        }
        usrTmp = null;
    }

    //将配对完成的玩家，转入战斗队列
    for (var m = (waitingrooms.length - 1); m >= 0; m--) {
        usrTmp = waitingrooms[m];
        if (waitingrooms[m].userState == userState.fight) {
            exports.ExitWaitingRoom(usrTmp);
            exports.EnterFightgingRoom(usrTmp);
            console.log("准备房间现有人数：" + waitingrooms.length);
        }
        //判断一下玩家的状态如果超时，则将玩家提出，让其重新匹配
        else if (waitingrooms[m].userState == userState.ready) {
            difTimeTmp = nowTime - waitingrooms[m].watingStartTime;
            if (difTimeTmp > c.watingMaxTime) {
                //waitingrooms.splice(util.findIndexEx(waitingrooms, waitingrooms[m].userId), 1);
                console.log("玩家等待超时，让玩家返回主界面");
                usrTmp.userstate = userState.leave;
                exports.ExitWaitingRoom(usrTmp);
            }
        }
        else {
            console.log(waitingrooms[m].userId + "玩家状态错误" + waitingrooms[m].userState);
            //waitingrooms.splice(util.findIndexEx(waitingrooms, waitingrooms[m].userId), 1);
            exports.ExitWaitingRoom(usrTmp);
        }
        usrTmp = null;
    }

}
/**绑定两个玩家 */
exports.connectUsers = function (userOne, userTwo, userstate = userState.ready) {
    if (userOne.userState != userstate || userTwo.userState != userstate) {
        console.log("玩家状态不对");
        return false;
    }
    userOne.fightUserId = userTwo.userId;
    userTwo.fightUserId = userOne.userId;
    userOne.userState = userState.fight;
    userTwo.userState = userState.fight;
    return true;
}

/************************************************************************************* */
/**进入邀请房间 */
exports.enterInvitingRoom = function (user) {
    //判断参数是否正常
    if (user == null) {
        console.log("玩家为空");
        return 6;
    }
    //判断参数是否正确
    if (exports.isUesrAlreadyInRoom(user, invitingRooms)) {
        console.log("玩家已经存在invitingRooms");
        return 7;
    }
    //判断是否反复加入房间
    //usermg.resetPlayer(user);
    user.userState = userState.invite;
    user.watingStartTime = nowTime;
    invitingRooms.push(user);
    console.log(user.userId + "玩家进入invitingRooms");
    return 0;
}
/**退出邀请房间 */
exports.ExitInvitingRoom = function (user) {
    if (user == null) {
        console.log("玩家为空");
        return false;
    }
    if (!exports.isUesrAlreadyInRoom(user, invitingRooms)) {
        console.log("玩家不存在invitingRooms");
        return false;
    }
    console.log(user.userId + "号玩家退出invitingRooms");
    let index = invitingRooms.indexOf(user);
    invitingRooms.splice(index, 1);
}

/**邀请房间配对 */
exports.InvitingRoomUpdate = function () {
    var usrTmp;
    var difTimeTmp;
    //将房间内玩家进行配对
    for (var i = 0; i < invitingRooms.length; ++i) {
        console.log(invitingRooms[i].userId + "玩家邀请函：" + invitingRooms[i].invitation);
        if (invitingRooms[i].invitation != -1) {
            usrTmp = exports.FindWhoInvites(invitingRooms[i]);
            if (usrTmp == null) {
                console.log(invitingRooms[i].userId + "玩家的邀请人已退出邀请房间");
                invitingRooms[i].userstate = userState.leave;
                exports.ExitInvitingRoom(invitingRooms[i]);
                continue;
            }
            if (exports.connectUsers(usrTmp, invitingRooms[i], userState.invite)) {
                console.log(invitingRooms[i].userId + "与" + usrTmp.userId + "绑定成功");
                break;
            }
            usrTmp = null;
        }

    }
    //将配对完成的玩家，转入战斗队列
    for (var m = (invitingRooms.length - 1); m >= 0; m--) {
        usrTmp = invitingRooms[m];
        if (invitingRooms[m].userState == userState.fight) {
            exports.ExitInvitingRoom(usrTmp);
            exports.EnterFightgingRoom(usrTmp);
            console.log("邀请房间现有人数：" + invitingRooms.length);
        }
        //判断一下玩家的状态如果超时，则将玩家提出，让其重新匹配
        else if (invitingRooms[m].userState == userState.invite) {
            difTimeTmp = nowTime - invitingRooms[m].watingStartTime;
            if (difTimeTmp > c.watingMaxTime) {
                //invitingRooms.splice(util.findIndexEx(invitingRooms, invitingRooms[m].userId), 1);
                console.log("玩家等待超时，让玩家返回主界面");
                ustmp.userstate = userState.leave;
                exports.ExitInvitingRoom(usrTmp);
            }
        }
        else {
            console.log(invitingRooms[m].userId + "玩家不是邀请状态" + invitingRooms[m].userState);
            //invitingRooms.splice(util.findIndexEx(invitingRooms, invitingRooms[m].userId), 1);
            exports.ExitInvitingRoom(usrTmp);
        }
        usrTmp = null;
    }

}
/**找到发送邀请的玩家 */
exports.FindWhoInvites = function (invitedUser) {
    console.log("遍历邀请房间：");
    for (let i = 0; i < invitingRooms.length; i++) {
        console.log(invitedUser.userId + "的邀请人：" + invitedUser.invitation + ",现有玩家" + invitingRooms[i].userId);
        if (invitingRooms[i].userId == invitedUser.invitation) {
            return invitingRooms[i];
        }
    }
    return null;
}
/************************************************************************************* */
/*** 战斗界面 */
/**/
exports.EnterFightgingRoom = function (user) {
    //判断参数是否正常
    if (user == null) {
        console.log("玩家为空");
        return false;
    }
    //判断参数是否正确

    if (exports.isUesrAlreadyInRoom(user, fightingrooms)) {
        console.log("玩家已经存在fightroom");
        return false;
    }
    userMgr.resetFightingPlayer(user);
    user.roundStartTime = nowTime;
    fightingrooms.push(user);
    console.log(user.userId + "号玩家进入fightingRoom");
    sr.gameStart(user.userId, 0);
}
/**结束战斗离开房间 */
exports.ExitFightingRoom = function (user) {
    if (user == null) {
        console.log("玩家为空");
        return false;
    }
    if (!exports.isUesrAlreadyInRoom(user, fightingrooms)) {
        console.log(user.userId + "玩家不在战斗房间");
        return false;
    }
    let index = fightingrooms.indexOf(user);
    fightingrooms.splice(index, 1);
    console.log(user.userId + "玩家退fightingRoom");
}
/**战斗队列的更新 
 * 1.遍历所有玩家判断回合是否到期，到期的话，则将另外玩家的消息转发
 * 2.将已经失败的玩家，从队列里面移除，并且发送胜负消息
 * 
 * 
*/
exports.fightingroomsUpdate = function () {
    var usrTmp;
    var difTimeTmp;
    //判断玩家是否已经结束，如果结束，则将玩家踢出
    for (var m = (fightingrooms.length - 1); m >= 0; m--) {
        if (fightingrooms[m].userState != userState.fight) {
            console.log(fightingrooms[m].userId + "玩家已经结束");
            //fightingrooms.splice(util.findIndexEx(fightingrooms, fightingrooms[m].userId), 1);
            fightingrooms.splice(m, 1);
        }

    }

    //将没结束的玩家，判断是否回合结束，如果结束则转发玩家消息
    for (var m = (fightingrooms.length - 1); m >= 0; m--) {

        difTimeTmp = nowTime - fightingrooms[m].roundStartTime;

        if (difTimeTmp > c.roundMaxTime) {
            /**转发玩家消息 */
            fightingrooms[m].roundStartTime = nowTime;
            userOther = userMgr.get(fightingrooms[m].fightUserId);
            if (userOther != null) {
                sr.Combatrequest(fightingrooms[m].userId, 0);
                console.log(fightingrooms[m].userId + "玩家进入下一轮");
                fightingrooms[m].isReadyToNext = false;
            }
        } else if (fightingrooms[m].isReadyToNext) {
            userOther = userMgr.get(fightingrooms[m].fightUserId);
            if (userOther != null && userOther.isReadyToNext) {
                fightingrooms[m].isReadyToNext = false;
                userOther.isReadyToNext = false;
                fightingrooms[m].roundStartTime = nowTime;
                userOther.roundStartTime = nowTime;
                sr.Combatrequest(fightingrooms[m].userId, 0);
                sr.Combatrequest(userOther.userId, 0);
            }
        } else {

        }



    }

}

/************************************************************************************* */



//用来表示房间内的时间循环
exports.update = function () {
    //  var keys = Object.keys(rooms);
    nowTime = new Date().getTime();
    //广播房间内所有玩家的消息
    exports.waitingroomsUpdate();
    exports.InvitingRoomUpdate();
    exports.fightingroomsUpdate();
}



/**根据玩家发消息 */
sendMsgByUser = function (u, movemsg) {
    if (u.socket == -1)
        return;
    if (u.socket != null) {
        try {
            sr.sendBitMessage(u.socket, JSON.stringify(movemsg))

        }
        catch (e) {
            console.log('new error..' + e);
        }
    }
    else {
        console.log('new error..' + u.name + '玩家的IP不存在');
    }
}





